//
//  NSTimerEx.swift
//  SubmitTransition
//
//  Created by Takuya Okamoto on 2015/08/06.
//  Copyright (c) 2015年 Uniface. All rights reserved.
//

import Foundation
private var timeCountDownClousure:(() -> ())?
extension Timer {
  class func schedule(delay _delay: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> CFRunLoopTimer? {
    let fireDate = _delay + CFAbsoluteTimeGetCurrent()
    let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    return timer
  }

  class func schedule(repeatInterval interval: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> CFRunLoopTimer? {
    let fireDate = interval + CFAbsoluteTimeGetCurrent()
    let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    return timer
  }

  class func schedule(oldTime time: TimeInterval, delayInterf delay: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> CFRunLoopTimer? {
    let interf = CFAbsoluteTimeGetCurrent() - time - delay
    if interf > 0 {
      handler(nil)
      return nil
    } else {
      let fireDate = time + delay
      let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
      CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
      return timer
    }
  }
  
  // MARK: --计时器(解决界面退出后timer无法释放的问题)
  /**
  - parameter timeMargin:    block的执行interval
  - parameter callBackBlock: block回调
  */
  class func countDownschedule(_ timeMargin:TimeInterval, callBackBlock:@escaping (() -> ())) -> Timer{
    timeCountDownClousure = callBackBlock
    let time = self.scheduledTimer(timeInterval: timeMargin, target: self, selector: #selector(Timer.excuteTimeCountDownClosure), userInfo: nil, repeats: true)
    
    RunLoop.current.add(time, forMode: RunLoopMode.commonModes)
    return time
  }

  @objc fileprivate class func excuteTimeCountDownClosure(){
    timeCountDownClousure!()
  }
}
